package org.ling.xuan.util;

import cn.hutool.core.util.StrUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LxStrUtil {

    /**
     * 将多行转换为map
     *
     * @param input 输入
     * @return {@link Map}<{@link String}, {@link String}>
     */
    public static Map<String, String> convertMultiLineToMap(String input,String mapSplit) {
        if(StrUtil.isNotBlank(input)){
            input=input.replace("\r\n","\n");
        }
        return convertToMap(input, "\n",mapSplit);
    }

    public static Map<String, String> convertToMap(String input, String itemSplit,String mapSplit) {
        Map<String, String> resultMap = new HashMap<>();
        if(StrUtil.isNotBlank(input)) {
            // 按行分割字符串
            String[] lines = input.split(itemSplit);
            for (String line : lines) {
                if (StrUtil.isNotBlank(line)) {
                    // 按冒号分割键值对
                    String[] keyValue = line.split(mapSplit, 2);
                    // 将键值对添加到Map中
                    if (keyValue.length == 2) {
                        resultMap.put(keyValue[0], keyValue[1]);
                    }
                }
            }
        }
        return resultMap;
    }

    /**
     * 给定 D:\svn-app  D:\svn-app\ifmonline\com.lcpt.aaa\AA.java 提取出ifmonline
     *
     * @param filePath 文件路径
     * @param path     路径
     * @return {@link String}
     */
    public static String extractPart(String path, String filePath) {
        unionPath(filePath);
        unionPath(path);
        int startIndex = path.length() + 1; // 加1是为了跳过路径后面的"/"
        int endIndex = filePath.indexOf("/", startIndex); // 查找从startIndex开始的下一个"/"位置
        if (endIndex == -1) {
            endIndex = filePath.length(); // 如果没有找到下一个"/"，则直接取到字符串末尾
        }
        return filePath.substring(startIndex, endIndex);
    }

    /**
     * 计算相对路径 给定 D:\svn-app  D:\svn-app\ifmonline\com.lcpt.aaa\AA.java 提取出ifmonline\com.lcpt.aaa\AA.java
     *
     * @param directory 目录
     * @param file      文件
     * @return {@link String}
     */
    public static String calculateRelativePath(File directory, File file) {
        String directoryPath = directory.getAbsolutePath();
        unionPath(directoryPath);
        String filePath = file.getAbsolutePath();
        unionPath(filePath);
        // Normalize the paths to handle differences in file separators and case sensitivity
        directoryPath = directoryPath.replace(File.separatorChar, '/');
        if (!directoryPath.endsWith("/")) {
            directoryPath = directoryPath + "/";
        }
        filePath = filePath.replace(File.separatorChar, '/');
        return filePath.substring(directoryPath.length());
    }

    public static String unionPath(String path) {
        if (StrUtil.isNotBlank(path)) {
            path = path.replace("\\\\", "/").replace("\\", "/");
        }
        return path;
    }

    public static boolean containsLeastOne(String s, String[] ss) {
        if (StrUtil.isNotBlank(s) && ss != null) {
            for (String a : ss) {
                if (StrUtil.isNotBlank(a) && s.contains(a)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static String startWithLeastOne(String s, List<String> ss) {
        if (StrUtil.isNotBlank(s) && ss != null) {
            for (String a : ss) {
                if (StrUtil.isNotBlank(a) && s.startsWith(a)) {
                    return a;
                }
            }
        }
        return "";
    }


    public static String convertUpdXmlToUpd(String xmlText) {
        try {
            InputSource is = new InputSource(new java.io.StringReader(xmlText));
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(is);
            doc.getDocumentElement().normalize();
            NodeList modList = doc.getElementsByTagName("lx-modifiy");
            StringBuilder sb  = new StringBuilder();
            List<String> itemContents = parseItemContents(xmlText);
            int itemCount = 0;
            for (int i = 0; i < modList.getLength(); i++) {
                Element mod = (Element) modList.item(i);
                String modNo = Optional.of(mod.getAttribute("modNo")).orElse("");
                String auth = Optional.of(mod.getAttribute("auth")).orElse("");
                String des = Optional.of(mod.getAttribute("des")).orElse("");
                String ano = StrUtil.format("-- add by {} {} {}",auth,des, modNo);
                sb.append(ano).append(" beg").append("\n");
                NodeList itemList = mod.getElementsByTagName("lx-item");
                for (int j = 0; j < itemList.getLength(); j++) {
                    Element item = (Element) itemList.item(j);
                    String index = String.valueOf(j+1);
                    String remark = item.getAttribute("remark");
                    sb.append("\t").append(index).append(".").append(remark).append("\n");
                    if(itemContents.size()<itemCount){
                        throw new RuntimeException("正则和xml解析item数量不匹配");
                    }
                    sb.append("\t\t\t\t").append(itemContents.get(itemCount)).append("\n");
                    itemCount++;
                }
                sb.append(ano).append(" end").append("\n");
            }
            return sb.toString();
        } catch (Exception e) {
            return xmlText;
        }
    }

    private static List<String> parseItemContents(String xmlText) {
        List<String> results = new ArrayList<>();
        Pattern pattern = Pattern.compile("<lx-item[^>]*>(.*?)</lx-item>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(xmlText);
        while (matcher.find()) {
            String itemContent = matcher.group(1);
            itemContent=itemContent.replace("\r\n","\n");
            results.add(itemContent);
        }
        return results;
    }
}
